<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>江西农业大学图书馆 - 管理系统</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @font-face {
            font-family: 'XingKai';
            src: url('https://cdn.jsdelivr.net/gh/googlefonts/noto-cjk@main/Sans/OTF/Chinese/NotoSansCJKsc-Bold.otf');
        }
        .system-title {
            font-family: 'XingKai', cursive;
            font-size: 28px;
            font-weight: bold;
            text-align: center;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1 class="system-title">江西农业大学图书馆</h1>
        <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">图书管理系统</a>
                <div class="collapse navbar-collapse">
                    <ul class="navbar-nav me-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="#" onclick="showBooks()">图书管理</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" onclick="showUsers()">用户管理</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" onclick="showBorrows()">借阅管理</a>
                        </li>
                    </ul>
                    <span class="navbar-text me-3" id="userInfo"></span>
                    <button class="btn btn-outline-danger" onclick="logout()">退出</button>
                </div>
            </div>
        </nav>
        <h2>图书管理系统</h2>
        <div class="row mt-3">
            <div class="col">
                <button class="btn btn-primary" onclick="showAddForm()">添加图书</button>
            </div>
        </div>
        <table class="table mt-3">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>书名</th>
                    <th>作者</th>
                    <th>出版日期</th>
                    <th>ISBN</th>
                    <th>库存</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="bookList">
            </tbody>
        </table>
        <div id="userManagement" style="display:none">
            <h3>用户管理</h3>
            <table class="table mt-3">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="userList">
                </tbody>
            </table>
        </div>
        <div id="borrowManagement" style="display:none">
            <h3>借阅记录管理</h3>
            <table class="table mt-3">
                <thead>
                    <tr>
                        <th>借阅ID</th>
                        <th>图书名称</th>
                        <th>借阅人</th>
                        <th>借阅日期</th>
                        <th>应还日期</th>
                        <th>实际归还日期</th>
                        <th>逾期费用</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="borrowList">
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加/编辑图书的模态框 -->
    <div class="modal fade" id="bookModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">添加图书</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="bookForm">
                        <input type="hidden" id="bookId">
                        <div class="mb-3">
                            <label class="form-label">书名</label>
                            <input type="text" class="form-control" id="bookName" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">作者</label>
                            <input type="text" class="form-control" id="bookAuthor" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">出版日期</label>
                            <input type="date" class="form-control" id="publishDate" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ISBN</label>
                            <input type="text" class="form-control" id="isbn" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">库存</label>
                            <input type="number" class="form-control" id="stock" required min="0">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">状态</label>
                            <select class="form-control" id="status">
                                <option value="1">可借阅</option>
                                <option value="0">不可借阅</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveBook()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加用户模态框 -->
    <div class="modal fade" id="userModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalTitle">添加用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="userForm">
                        <input type="hidden" id="userId">
                        <div class="mb-3">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-control" id="userUsername" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">密码</label>
                            <input type="password" class="form-control" id="userPassword" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">角色</label>
                            <select class="form-control" id="userRole">
                                <option value="0">普通用户</option>
                                <option value="1">管理员</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let bookModal;
        let userModal;
        let currentUser;
        
        document.addEventListener('DOMContentLoaded', function() {
            bookModal = new bootstrap.Modal(document.getElementById('bookModal'));
            userModal = new bootstrap.Modal(document.getElementById('userModal'));
            currentUser = JSON.parse(localStorage.getItem('user'));
            
            if (!currentUser) {
                window.location.href = 'login.html';
                return;
            }
            
            document.getElementById('userInfo').textContent = `当前用户：${currentUser.username}`;
            if (currentUser.role === 1) {
                document.querySelectorAll('.admin-only').forEach(el => el.style.display = 'block');
            }
            
            loadBooks();
        });

        // 加载图书列表
        function loadBooks() {
            fetch('/api/books')
                .then(response => response.json())
                .then(books => {
                    const bookList = document.getElementById('bookList');
                    bookList.innerHTML = '';
                    books.forEach(book => {
                        bookList.innerHTML += `
                            <tr>
                                <td>${book.id}</td>
                                <td>${book.name}</td>
                                <td>${book.author}</td>
                                <td>${formatDate(book.publishDate)}</td>
                                <td>${book.isbn}</td>
                                <td>${book.stock}</td>
                                <td>${book.status === 1 ? '可借阅' : '不可借阅'}</td>
                                <td>
                                    <button class="btn btn-sm btn-warning" onclick="editBook(${book.id})">编辑</button>
                                    <button class="btn btn-sm btn-danger" onclick="deleteBook(${book.id})">删除</button>
                                </td>
                            </tr>
                        `;
                    });
                });
        }

        // 显示添加图书表单
        function showAddForm() {
            document.getElementById('modalTitle').textContent = '添加图书';
            document.getElementById('bookForm').reset();
            document.getElementById('bookId').value = '';
            bookModal.show();
        }

        // 编辑图书
        function editBook(id) {
            document.getElementById('modalTitle').textContent = '编辑图书';
            fetch(`/api/books/${id}`)
                .then(response => response.json())
                .then(book => {
                    document.getElementById('bookId').value = book.id;
                    document.getElementById('bookName').value = book.name;
                    document.getElementById('bookAuthor').value = book.author;
                    document.getElementById('publishDate').value = formatDate(book.publishDate);
                    document.getElementById('isbn').value = book.isbn;
                    document.getElementById('stock').value = book.stock;
                    document.getElementById('status').value = book.status;
                    bookModal.show();
                });
        }

        // 保存图书
        function saveBook() {
            const book = {
                name: document.getElementById('bookName').value,
                author: document.getElementById('bookAuthor').value,
                publishDate: document.getElementById('publishDate').value,
                isbn: document.getElementById('isbn').value,
                stock: parseInt(document.getElementById('stock').value),
                status: parseInt(document.getElementById('status').value)
            };

            const id = document.getElementById('bookId').value;
            const url = id ? `/api/books/${id}` : '/api/books';
            const method = id ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(book)
            })
            .then(response => response.json())
            .then(result => {
                if(result) {
                    bookModal.hide();
                    loadBooks();
                    alert(id ? '更新成功' : '添加成功');
                } else {
                    alert('操作失败');
                }
            });
        }

        // 删除图书
        function deleteBook(id) {
            if(confirm('确定要删除这本书吗？')) {
                fetch(`/api/books/${id}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(result => {
                    if(result) {
                        loadBooks();
                        alert('删除成功');
                    } else {
                        alert('删除失败');
                    }
                });
            }
        }

        // 格式化日期
        function formatDate(date) {
            if (!date) return '';
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }

        function showBooks() {
            document.getElementById('bookManagement').style.display = 'block';
            document.getElementById('userManagement').style.display = 'none';
        }
        
        function showUsers() {
            document.getElementById('bookManagement').style.display = 'none';
            document.getElementById('borrowManagement').style.display = 'none';
            document.getElementById('userManagement').style.display = 'block';
            loadUsers();
        }
        
        function loadUsers() {
            fetch('/api/users')
                .then(response => response.json())
                .then(users => {
                    const userList = document.getElementById('userList');
                    userList.innerHTML = '';
                    users.forEach(user => {
                        userList.innerHTML += `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.username}</td>
                                <td>${user.role === 0 ? '普通用户' : '管理员'}</td>
                                <td>
                                    <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">删除</button>
                                </td>
                            </tr>
                        `;
                    });
                });
        }
        
        function showAddUserForm() {
            document.getElementById('userModalTitle').textContent = '添加用户';
            document.getElementById('userForm').reset();
            document.getElementById('userId').value = '';
            userModal.show();
        }
        
        function saveUser() {
            const user = {
                username: document.getElementById('userUsername').value,
                password: document.getElementById('userPassword').value,
                role: parseInt(document.getElementById('userRole').value)
            };
            
            const id = document.getElementById('userId').value;
            const url = id ? `/api/users/${id}` : '/api/users';
            const method = id ? 'PUT' : 'POST';
            
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(user)
            })
            .then(response => response.json())
            .then(result => {
                if(result) {
                    userModal.hide();
                    loadUsers();
                    alert(id ? '更新成功' : '添加成功');
                } else {
                    alert('操作失败');
                }
            });
        }
        
        function deleteUser(userId) {
            if(confirm('确认删除该用户？')) {
                fetch(`/api/users/${userId}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if(response.ok) {
                        alert('用户删除成功');
                        loadUsers();
                    } else {
                        alert('用户删除失败');
                    }
                });
            }
        }
        
        function logout() {
            fetch('/api/users/logout', {
                method: 'POST'
            })
            .then(() => {
                localStorage.removeItem('user');
                window.location.href = 'login.html';
            });
        }

        function showBorrows() {
            document.getElementById('bookManagement').style.display = 'none';
            document.getElementById('userManagement').style.display = 'none';
            document.getElementById('borrowManagement').style.display = 'block';
            loadBorrows();
        }

        function loadBorrows() {
            fetch('/api/borrows')
                .then(response => response.json())
                .then(borrows => {
                    const borrowList = document.getElementById('borrowList');
                    borrowList.innerHTML = '';
                    borrows.forEach(borrow => {
                        borrowList.innerHTML += `
                            <tr>
                                <td>${borrow.id}</td>
                                <td>${borrow.bookName}</td>
                                <td>${borrow.userName}</td>
                                <td>${formatDate(borrow.borrowDate)}</td>
                                <td>${formatDate(borrow.returnDate)}</td>
                                <td>${formatDate(borrow.actualReturnDate) || '-'}</td>
                                <td>${borrow.overdueFee ? '￥' + borrow.overdueFee : '-'}</td>
                                <td>${getBorrowStatus(borrow)}</td>
                                <td>
                                    ${borrow.status === 0 ? 
                                      `<button class="btn btn-sm btn-success" onclick="handleReturn(${borrow.id})">处理归还</button>` 
                                      : ''}
                                </td>
                            </tr>
                        `;
                    });
                });
        }

        function getBorrowStatus(borrow) {
            if (borrow.status === 1) return '已归还';
            return new Date() > new Date(borrow.returnDate) ? '已逾期' : '借阅中';
        }

        function handleReturn(borrowId) {
            if(confirm('确认处理归还？')) {
                fetch(`/api/borrows/${borrowId}/return`, {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(result => {
                    if(result) {
                        alert('归还处理成功');
                        loadBorrows();
                    } else {
                        alert('归还处理失败');
                    }
                });
            }
        }
    </script>
</body>
</html> 